package pl.mess.core.tags.elements;

import pl.mess.core.uiobjects.MESSTreeView;
import pl.mess.core.uiobjects.MESSTreeViewElement;
import pl.mess.core.tags.ifc.ControlAttribute;

import javax.servlet.jsp.JspException;
import javax.servlet.ServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: gibffe
 * Date: Apr 4, 2006
 * Time: 7:33:22 PM
 * To change this template use File | Settings | File Templates.
 */
public class MESSTreeViewTag extends MESSBaseTag {

    private static final String TAG_NAME = "treeView";

    /**
     * paremeter defining request scope object name containing tree data
     */
    @ControlAttribute public String source = null;


    public String getTagName() {
        return TAG_NAME;
    }

    /**
    * StartTag method
    * @return
    * @throws javax.servlet.jsp.JspException
    */
    public int doStartTag() throws JspException {

        super.doStartTag();

        // get tree source from scope
        ServletRequest request = this.getPageContext().getRequest();
        MESSTreeView tree = (MESSTreeView) request.getAttribute(this.source);

        for (Iterator it = tree.getElements().iterator(); it.hasNext();) {
            // recursively render tree elements
            MESSTreeViewElement el = (MESSTreeViewElement) it.next();
            this.writeTreeElement(el);
        }


        return this.evalBody();
    }

    /**
     * Recursively render tree element
     * @param element
     */
    private void writeTreeElement(MESSTreeViewElement element) {

        MESSTreeViewElementTag elTag = new MESSTreeViewElementTag(this.getWriter(), element);

        // write header
        elTag.writeTagStart();

        // render child elements
        for (Iterator it = element.getElements().iterator(); it.hasNext();) {
            MESSTreeViewElement el = (MESSTreeViewElement) it.next();
            this.writeTreeElement(el);
        }

        // write tail
        elTag.writeTagEnd();
    }

    /**
    * EndTag method
    * @return
    * @throws JspException
    */
    public int doEndTag() throws JspException {

        return super.doEndTag();
    }


    // parameter: source
    public void setSource(String source) {
        this.source = source;
    }
}
